import { createApp } from 'vue'
import { createPinia } from 'pinia'
import { defineDirectives } from '@/directives/index.js'
import { defineProperties } from '@/properties/index.js'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
import { useUserStore } from '@/stores/userInfo.js'
import { usePublicStore } from '@/stores/publicInfo.js'
import App from './App.vue'
import router from './router'
import { basicRouters } from './router'
import { isAuthenticated } from '@/utils/auth.js'

const app = createApp(App)

// 添加全局方法
defineProperties(app)
//注册自定义指令
defineDirectives(app)
//引入全局规范样式
import './scss/index.scss'
// 引入iconfont symbol方式引入 主要用于菜单栏图标
import './assets/iconfonts/iconfont.js'

app.use(createPinia())
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
app.use(pinia)

// 获取用户Store
const userStore = useUserStore()
const publicStore = usePublicStore()
// 等待用户数据和路由恢复，解决刷新页面后，动态添加路由消失问题
Promise.all([userStore.initUserData(), publicStore.getMiddleTable()]).finally(() => {
  // 初始化路由
  app.use(router)
  app.mount('#app')
})

router.beforeEach(async (to) => {
  document.title = to.meta.title || '智慧系统'
  // 基础路由白名单
  const whiteList = basicRouters.map((el) => el.path)
  //基础路由白名单直接跳转
  if (whiteList.includes(to.path)) {
    return true
  } else {
    //没有token跳转到登录
    if (!isAuthenticated()) {
      return '/login'
    }
    if (!router.hasRoute(to.name)) {
      return '/login'
      // try {
      //   const initSuccess = await userStore.initUserData()
      //   if (!initSuccess) return '/login'
      //   return to.fullPath // 重试导航
      // } catch (error) {
      //   return '/login'
      // }
    }
  }
})
